#!/usr/bin/env node

const { program } = require('commander');
const chalk = require('chalk');
const package = require('./package.json');
const fetch = require('node-fetch');

program
    .name('IP Address Query')
    .description('A command line tool of ip address query.')
    .version(package.version, '-v, --version', 'output the current version')
    .on('--help', () => {
        console.log();
        console.log(chalk.gray('Examples：'));
        console.log(chalk.blueBright('  $'), 'ip | IP');
    });
program.parse(process.argv);

const getIP = async() => {
    let url = 'https://www.taobao.com/help/getip.php';
    return fetch(url)
        .then((response) => response.text())
        .then((data) => data.match(/\d.*\d/)[0])
        .catch((error) => console.log(error));
};

const getAddr = async(ip) => {
    let key = 'ec3dd6d7c35413cbe888551e8f7916d0';
    let type = 4;
    let url = `https://restapi.amap.com/v5/ip?key=${key}&type=${type}&ip=${ip}`;
    return fetch(url)
        .then((response) => response.json())
        .then((data) => {
            const { country, province, city, district, isp, location } = data;
            console.log();
            console.log(chalk.green.bold(`当前IP： ${ip}  来自于：${country}${province}${city}${district}  运营商：${isp}  经纬度：${location}`));
            console.log();
        })
        .catch((error) => console.log(error));
};

const callAsync = async() => {
    let ip = await getIP();
    await getAddr(ip);
};

callAsync();